package cn.jdy.plugins.admin;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.http.client.utils.DateUtils;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.Organ;
import cn.jdy.authority.entity.User;
import cn.jdy.authority.entity.UserRole;
import cn.jdy.authority.service.OrganService;
import cn.jdy.authority.service.UserRoleService;
import cn.jdy.authority.service.UserService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.HttpUtil;
import cn.jdy.framework.util.JsonUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.admin.export.EvaluationzhliveExcelView;
import cn.jdy.plugins.entity.Line;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.service.AdvertisingService;
import cn.jdy.plugins.service.ChatService;
import cn.jdy.plugins.service.LabelService;
import cn.jdy.plugins.service.LineService;
import cn.jdy.plugins.service.LiveService;
import cn.jdy.plugins.service.PptImgService;
import cn.jdy.plugins.service.RedPacketReceiveService;
import cn.jdy.plugins.service.RelatedVideoService;
import cn.jdy.plugins.service.VisitLogService;
import cn.jdy.plugins.web.liveCtrl;








/**
 * @title 直播控制类
 * @author lutan
 */
@Controller
@RequestMapping("/live")
public class LiveCtrl extends BaseCtrl {
	@Autowired
	private LineService lineService;
	@Autowired
	private RelatedVideoService relatedVideoService;
	@Autowired
	private RedPacketReceiveService redPacketReceiveService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private UserService userService;
	@Autowired
	private LiveService LiveService;
	@Autowired
	private ChatService chatService;
	@Autowired
	private ConfService confService;
	@Autowired
	private LabelService labelService;
	@Autowired
	private AdvertisingService advertisingService;
	@Autowired
	private VisitLogService visitLogService;
	@Autowired
	private PptImgService pptImgService;
	@Autowired
	protected HttpSession session;
	@Autowired
	private OrganService organService;
	// 默认列表路径
	private static String viewName = "redirect:/live/list?s=";

	/**
	 * 初始化
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(required = false) Integer s) {
	    String path = request.getSession().getServletContext().getRealPath("/");
	    System.out.println(path+"---1111111");
	    String currentPath = new File(path).getParent()+"/ddd";
	    System.out.println(currentPath+"---");
		ModelAndView mv = new ModelAndView();
		if (s != null)
			switch (s) {
			case 1:
				mv.addObject("msg", "保存成功！");
				break;
			case 2:
				mv.addObject("msg", "更新成功！");
				break;
			case 3:
				mv.addObject("msg", "删除成功！");
				break;
			case 4:
				mv.addObject("msg", "操作失败！");
				break;
			default:
				break;
			}
		User user = (User) session.getAttribute("user");
		mv.addObject("iTotalRecords", LiveService.count("userid",user.getId()));
		mv.setViewName("/operate/liveList.jsp");
		return mv;
	}

	/**
	 * 异步查询
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(Live live,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			User user = (User) session.getAttribute("user");
			List<UserRole> list = userRoleService.find("userid", user.getId());
			String roleid = "";
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getRoleid()
						.equals("4028b3044de1a396014de1ba2b2e0000")
						|| list.get(i).getRoleid()
								.equals("ff8080814db89f0a014db8d169290000")) {
					roleid = "0";
				}
			}
			if (roleid != "0") {
				String s="";
				if(user.getZlineid()!=null){
				String a[]=user.getZlineid().split(",");
				
						for (int i = 0; i < a.length; i++) {
							if(a.length>0){
								s +="'"+a[i]+"',";
							}
						}
						if (a.length>0) {
							s=s.substring(0, s.length()-1);
						} else {
							s=user.getZlineid();
						}
				}else{
					s="'0'";
				}
						String	name="";
				if(!live.getName().equals("")){//根据名字查询
						name="and name like '%"+live.getName()+"%' ";
				}
				String 	status="";
				if(!live.getStatus().equals("")){//根据状态查询
						status="and status='"+live.getStatus()+"' ";
				}
				String createTime="";
				if(!fromDate.equals("")&&!toDate.equals("")){//根据时间查询
					createTime="and createTime BETWEEN '"+fromDate+"' AND '"+toDate+"'";
			}
				jsonMap.put("dataList", LiveService.querySiteMap(s,name,status,createTime,live.getiDisplayStart(),live.getiDisplayLength()));
				jsonMap.put("iTotalDisplayRecords", LiveService.countquery(s, name, status, createTime));
				jsonMap.put("iTotalRecords", LiveService.countquery(s, name, status, createTime));
			}else{
				jsonMap.put("dataList", LiveService.query(live,fromDate, toDate));
				jsonMap.put("iTotalDisplayRecords", LiveService.count(live));
				jsonMap.put("iTotalRecords", LiveService.count(live));
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	/**
	 * 新增
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/liveDetail.jsp");
		User user = (User) session.getAttribute("user");
		List<UserRole> list = userRoleService.find("userid", user.getId());
		String roleid = "";
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getRoleid()
					.equals("4028b3044de1a396014de1ba2b2e0000")
					|| list.get(i).getRoleid()
							.equals("ff8080814db89f0a014db8d169290000")) {
				roleid = "0";
			}
		}
		if (roleid != "0") {
			
			mv.addObject("zlineid",
					userService.findOne("id", user.getId())
							.getZlineid());
			mv.addObject("linedata", lineService.find("organid", userService
					.findOne("username", user.getUsername()).getOrganid()));
		} else {
			mv.addObject(
					"zlineid",
					userService.findOne("id",
							LiveService.find(id).getUserid()).getZlineid());
			mv.addObject("linedata", lineService.findAll());
		}
		mv.addObject("data",
				id == null || id == 0 ? id : this.LiveService.find(id));
		return mv;
	}

	/**
	 * 保存（更新）直播
	 * 
	 * @param Live
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping("/save")
	public ModelAndView save(Live Live) {
		ModelAndView mv = new ModelAndView();
		User user = (User) session.getAttribute("user");
		try {
			Live.setMainurl(lineService.findOne("id",Live.getMainid()).getUrl());
			Live.setMainname(lineService.findOne("id",Live.getMainid()).getName());
			Live.setLiveurl(Live.getMainurl());
			if (!Live.getBackid().equals("")) {
				Live.setBackurl(lineService.findOne("id",Live.getBackid()).getUrl());
				Live.setBackname(lineService.findOne("id",Live.getBackid()).getName());	
			}
			List<UserRole> list = userRoleService.find("userid", user.getId());
			String roleid = "";
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getRoleid()
						.equals("4028b3044de1a396014de1ba2b2e0000")
						|| list.get(i).getRoleid()
								.equals("ff8080814db89f0a014db8d169290000")) {
					roleid = "0";
				}
			}
			if (roleid != "0") {
				Live.setUserid(user.getId());
			}
			if (Live.getId() == null) {
				Live.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				Live.setAppid(userService.findOne("username",user.getUsername())
						.getOrganid());
				this.LiveService.save(Live);
				this.labelService.insertlabel(Live.getId(),Live.getUserid());
				mv.setViewName(this.viewName.concat("1"));
			} else {
				Live.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				Live.setAppid(userService.findOne("id",Live.getUserid())
						.getOrganid());
			
				Live live2=LiveService.find(Live.getId());
				if(!live2.getFromDate().equals(Live.getFromDate())){
					toUpdateLivedata(Live.getId(),Live.getFromDate(),Live.getName());
				}
				if(!live2.getName().equals(Live.getName())){
					toUpdateLivedata(Live.getId(),Live.getFromDate(),Live.getName());
				}
				this.LiveService.update(Live);
				mv.setViewName(this.viewName.concat("2"));
				// 清理内容页缓存
				NginxPurgeCacheUtil.purge(6, Live.getId());
			}
			// 清理内容页缓存
			NginxPurgeCacheUtil.purge(5, Live.getId());
		} catch (Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "直播保存异常", e);
		}
		return mv;
	}

	
	/**
	 *  
	 * 
	 * @param
	 * @return
	 * @throws ParseException 
	 */
	public Map<String, Object> toUpdateLivedata(Long id,String fromDate,String name ) throws ParseException {
		@SuppressWarnings("unused")
		Map<String, Object> jsonMap = new HashMap<String, Object>();
	
	
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟  
			java.util.Date date=sdf.parse(fromDate);  
			 

			String vre = HttpUtil.sendGet("http://www.iyunfa.cn/app/index.php?i=102&c=entry&do=Updatetime&m=zhibo&liveid="+id+"&time="+date.getTime()+"&livename="+ URLEncoder.encode(name, "utf-8")+"" ,"UTF-8");
			 
			System.out.println(vre);
	 
		//	System.out.println("http://www.iyunfa.cn/app/index.php?i=102&c=entry&do=Updatetime&m=zhibo&liveid="+id+"&time="+date.getTime()+"&livename='"+ name+"'");
				BaseLog.i(this.getClass(), jsonMap + ">>>>>.>>>>>user");
			System.out.println(jsonMap);
				// System.out.println(oep + ">>>>>.>>>>>user ");
		
		} catch (IOException e) {
			e.printStackTrace();
			BaseLog.e(this.getClass(), "失败！", e);
		}

		return jsonMap;
		
	}
	
public static void main(String[] args) throws ParseException {
	LiveCtrl lc=new LiveCtrl();
	lc.toUpdateLivedata(3042L, "2017-11-06 15:56:01", "世界防艾日“共担防艾责任，共享健康权利，共建健康中国”");
	lc.isflopen(3042L);
}
	public static String string2Unicode(String string) {
		 
	    StringBuffer unicode = new StringBuffer();
	 
	    for (int i = 0; i < string.length(); i++) {
	 
	        // 取出每一个字符
	        char c = string.charAt(i);
	 
	        // 转换为unicode
	        unicode.append("\\u" + Integer.toHexString(c));
	    }
	 
	    return unicode.toString();
	}
	/**
	 * 删除直播
	 * 
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.advertisingService.delete("liveId", id);
			this.relatedVideoService.delete("liveId", id);
			this.labelService.delete("liveid",id);
			this.chatService.delete("liveId",id);
			this.redPacketReceiveService.delete("liveId", id);
			this.visitLogService.delete("liveId", id);
			this.pptImgService.delete("liveid",id);
			this.LiveService.delete("id",id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理内容页缓存
			NginxPurgeCacheUtil.purge(6, id);
		} catch (Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除直播异常！", e);
		}
		return mv;
	}

	/**
	 * 状态切换
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping("/statusSwitch")
	@ResponseBody
	public Map<String, Object> statusSwitch(Long id, String status, String isrobot) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();		

		try {
			Live live = LiveService.find(id);
			if (live != null) {
			
				if (!StringUtil.isNullOrEmpty(status)) {
					live.setStatus(status);
				}
				if (!StringUtil.isNullOrEmpty(isrobot)) {
					live.setIsrobot(isrobot);
				}
			
				live.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				LiveService.update(live);
				User user = getUser();
				
				//String json = "{liveId:"+live.getId()+" ,chatType:'6',status:'"+live.getStatus()+"',liveurl:'"+live.getLiveurl()+"',"
				//		+ "moviurl:'"+live.getMoviurl()+"',backmoviurl:'"+live.getBackmoviurl()+"',username:'"+user.getUsername()+"',upass:'"+user.getPasswd()+"'  }";
		    //	TextMessage textMessage = new TextMessage(json);
			
				live.setMoviurl(user.getUsername());
				live.setBackmoviurl(user.getPasswd());
				jsonMap.put("obj", live);
		//		WebliveWebsocket websocket=new WebliveWebsocket();
		//		将客户端发送的信息输出给所有在线人员
			//	TextMessage textMessage = new TextMessage(json);
				//o1hlOt4JXrwBp_vLswMfw4MZ02Gw
		    	//websocket.sendMessageToUser("o1hlOt4JXrwBp_vLswMfw4MZ02Gw",textMessage);
		    	

			} else {

			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "状态切换异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 导播地址and直播地址
	 * @author LPH
	 * @param
	 * @return
	 */
	@RequestMapping("/directorUrl")
	@ResponseBody
	public Map<String, Object> directorUrl(Long liveId, String status) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		//String urls=request.getSession().getServletContext().getRealPath("/");
		//String u=request.getLocalAddr();
		//int port=request.getLocalPort();
		//获取域名
	//	StringBuffer urls = request.getRequestURL();
	//	String stra = urls.toString().split(":")[1];
	//	String Url = stra.substring(2, stra.length());
		String Url = request.getHeader("Host2") ;
		//String Url = urls.delete(urls.length() - request.getRequestURI().length(), urls.length()).toString();
		try {
			String url = null;
			int str = 0 ;
			if(status.equals("1")){
				url="http://"+Url+"/"+"w"+"/"+"guide"+"/"+liveId+"."+"html";
				str=1;
			}else{
				url="http://"+Url+"/"+"lives"+"/"+"liveindex"+"/"+liveId;
				str=2;
			}
			jsonMap.put("url",url);
			jsonMap.put("status",str);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "状态切换异常", e);
		}
		return jsonMap;
	}
	
//	/**
//	 * 直播地址
//	 * @param
//	 * @return
//	 */
//	@RequestMapping("/liveurl")
//	@ResponseBody
//	public Map<String, Object> liveUrl(Long liveId, String status) {
//		Map<String, Object> jsonMap = new HashMap<String, Object>();
//		//String urls=request.getSession().getServletContext().getRealPath("/");
//		//String u=request.getLocalAddr();
//		//int port=request.getLocalPort(); 
//		try {
//			String url ="http://011.cc"+"/"+"lives"+"/"+"liveindex"+"/"+liveId;
//			jsonMap.put("url",url);
//			jsonMap.put("status",2);
//		} catch (Exception e) {
//			BaseLog.e(this.getClass(), "状态切换异常", e);
//		}
//		return jsonMap;
//	}
	
	/**
	 * 获取所有主题
	 * 
	 * @return
	 */
	@RequestMapping("/queryAllKindergarten")
	@ResponseBody
	public Map<String, Object> queryAllKindergarten() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList",confService.queryByType(52,Long.valueOf(0), null));
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 获取主题下的模版
	 * 
	 * @return
	 */
	@RequestMapping("/queryAllInterestClass")
	@ResponseBody
	public Map<String, Object> queryAllInterestClass(
			@RequestParam(value = "kId", required = false) Long kId) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			List<ConfValue> list = confService.queryByType(52,kId, null);
			jsonMap.put("intList", list);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 获取主题下的模版的预览图片
	 * 
	 * @return
	 */
	@RequestMapping("/queryAllInterestClass1")
	@ResponseBody
	public Map<String, Object> queryAllInterestClass1(
			@RequestParam(value = "id", required = false) Long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			List<ConfValue> list =confService.find("id",id);
			jsonMap.put("intList", list);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 获取当前直播的统计图表
	 * 
	 * @return
	 */
	@RequestMapping("/countLive")
	public ModelAndView countLive(Live obj) {
		ModelAndView mv = new ModelAndView();
		
		mv.addObject("data",obj);

		mv.setViewName("/countLive/countLive.jsp");
		return mv;
	}
	/**
	 * 异步查询统计这个直播访问综合信息
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/liveCountQueryByPage")
	@ResponseBody
	public Map<String, Object> liveCountQueryByPage(Live live,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
		
				jsonMap.put("dataList", LiveService.liveCountQuery(live,fromDate, toDate));
				jsonMap.put("iTotalDisplayRecords", 1);
				jsonMap.put("iTotalRecords", 1);

		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 导出统计综合记录
	 * @param evaluationRecord
	 * @param fromDate
	 * @param toDate
	 * @param model
	 * @return
	 */
	@RequestMapping("/exliveCountQueryByPage")
	public ModelAndView exliveCountQueryByPage(Live live,String fromDate, String toDate,ModelMap model) {
	    List<Map<String, Object>> list = LiveService.liveCountQuery(live,fromDate, toDate);
	    model.put("dataSet", list);
	    model.put("searchDate", fromDate+"-"+toDate);
	    EvaluationzhliveExcelView evaluationRecordExcelView = new EvaluationzhliveExcelView();
	    return new ModelAndView(evaluationRecordExcelView, model);
	}
	
	/**
	 * 异步查询统计这个直播访问是否接入法律平台
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/isflopen")
	@ResponseBody
	public Map<String, Object> isflopen(Long id) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
		int lssist=	LiveService.isflopen(id).size();
			if(lssist>0){
				Live live = LiveService.find(id);
				if (null != live) {
				// 获取线路信息
				Line line = lineService.find(live.getMainid());
				Organ weixin = organService.find(line.getOrganid());
				
				String vre = HttpUtil.sendGet("http://www.iyunfa.cn/app/index.php?i=102&c=entry&do=GetUniacid&m=zhibo&appid="+weixin.getAppId()+"&liveid="+id ,"UTF-8");
				jsonMap.put("msg",vre );
				}
			}else{
				jsonMap.put("msg","0" );
			}
		    
			

		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
			jsonMap.put("msg","0" );
		}
		return jsonMap;
	}
  
}
